package com.example.app2;

import android.app.Application;
import android.content.res.Configuration;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Environment;
import android.util.Log;

import androidx.annotation.NonNull;
import androidx.room.Room;
import androidx.room.RoomDatabase;

import com.example.app2.pojo.GoodsInfo;
import com.example.app2.util.FileUtil;
import com.example.app2.util.SharedUtil;

import java.io.File;
import java.util.List;

public class MyApplication extends Application {
    String TAG="tang";
    private BookDatabase bookDatabase;
    //已经添加到购物车中的商品数量
    public int goodsCount=0;
    static MyApplication app=null;
    @Override
    public void onCreate() {
        super.onCreate();
        Log.d(TAG, "Application onCreate: ");
        app=this;
        bookDatabase= Room.databaseBuilder(this,BookDatabase.class,"bookinfo")
                // 允许迁移数据库（发生数据库变更时，Room默认删除原数据库再创建新数据库。如此一来原来的记录会丢失，故而要改为迁移方式以便保存原有记录）
                .addMigrations()
                // 允许在主线程中操作数据库（Room默认不能在主线程中操作数据库）
                .allowMainThreadQueries()
                .build();
        //初始化商品信息
        initGoodsInfo();
    }

    private void initGoodsInfo() {
        //获取参数看是否是第一次打开
        boolean first = SharedUtil.getInstance(this).readBoolean("first");
        if(first)
        {
            String directory=getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS).toString()+ File.separatorChar;
            //模拟网络环境下载
            List<GoodsInfo> list=GoodsInfo.getDefaultList();
            for (GoodsInfo info : list) {
                String path=directory+info.id+".jpg";
                Bitmap bitmap = BitmapFactory.decodeResource(getResources(), info.pic);
                //往存储卡保存商品图片
                FileUtil.saveImage(path,bitmap);
                //回收位图对象
                bitmap.recycle();
                info.picPath=path;
            }
            //打开数据库，将商品信息插入到列表中
            ShoppingDBHelper dbHepler=ShoppingDBHelper.getInstance(this);
            dbHepler.openWriteLink();
            dbHepler.insertGoodsInfo(list);
            dbHepler.closeLink();

            //把是否是再次写入保存到共享参数
            SharedUtil.getInstance(this).writeBooolean("first",false);
        }
    }
    public BookDatabase getBookDatabase()
    {
        return bookDatabase;
    }
    public static MyApplication getInstance()
    {
        return app;
    }
    @Override
    public void onTerminate() {
        super.onTerminate();
        Log.d(TAG, "Application onTerminate: ");
    }

    @Override
    public void onConfigurationChanged(@NonNull Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        Log.d(TAG, "Application onConfigurationChanged: ");
    }

}
